﻿using ChunQiu.Arch.Session.Core.ConfigSection;
using ChunQiu.Arch.Session.Core.Models;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace Framework.Zhaogang.Session.Core
{
    class Helper
    {
        public static bool ParseSessionID(string rawSessionId, out string prefix, out string realSessionId)
        {
            prefix = string.Empty;
            realSessionId = string.Empty;

            if (rawSessionId == null)
                return false;
            if (rawSessionId.Trim().Length == 0)
                return false;
            string[] parsedValues = rawSessionId.Split('.');
            if (parsedValues == null)
                return false;
            if (parsedValues.Length != 2)
                return false;

            prefix = parsedValues[0];
            realSessionId = parsedValues[1];

            return true;
        }

        public static string Serialize(SessionStateItemCollection items)
        {
            MemoryStream ms = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(ms);

            if (items != null)
                items.Serialize(writer);

            writer.Close();

            return Convert.ToBase64String(ms.ToArray());
        }

        public static SessionStateStoreData Deserialize(HttpContext context, string serializedItems, int timeout)
        {
            MemoryStream ms = null;
            if (serializedItems != null && serializedItems.Trim().Length > 0)
                ms = new MemoryStream(Convert.FromBase64String(serializedItems));

            SessionStateItemCollection sessionItems =
              new SessionStateItemCollection();

            if (ms != null && ms.Length > 0)
            {
                BinaryReader reader = new BinaryReader(ms);
                sessionItems = SessionStateItemCollection.Deserialize(reader);
            }

            return new SessionStateStoreData(sessionItems,
              SessionStateUtility.GetSessionStaticObjects(context),
              timeout);
        }

        /// <summary>
        /// 获取集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static MongoCollection<T> GetMongoDBCollection<T>()
        {
            var url = new MongoUrl(ConfigurationManager.ConnectionStrings["SessionDB"].ConnectionString);
            var client = new MongoClient(url);
            var database = client.GetServer().GetDatabase(url.DatabaseName);
            return database.GetCollection<T>(SessionProviderSettings.GetSettings().SessionProfix, WriteConcern.Unacknowledged);
        }
    }
}
